package com.probox.modules.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.entity.domain.wechat.AppletInfo.AppealRecord;
import com.probox.common.entity.domain.wechat.WechatAppletInfo;
import com.probox.common.entity.domain.wechat.vo.CanSetCategoryInfoVo;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.common.entity.service.wechat.WechatPayAuditService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 快速注册小程序
 *
 * @author usoft
 * @date 2021-05-28
 */
@RestController
@RequestMapping("/wechat/applet")
public class WechatAppletInfoController extends BaseController {

    @Autowired
    private WechatMiniService wechatMiniService;

    @Autowired
    private WechatPayAuditService wechatPayAuditService;


    /**
     * 获取基本信息
     * @authorizerAppid 授权方appid
     */
    @GetMapping("/getAppletInfo")
    public WechatAppletInfo AppletInfo(@RequestBody String authorizationType){
        WechatAppletInfo wechatAppletInfo = wechatMiniService.getAppletInfo(authorizationType);
        logger.info("获取基本信息为："+ wechatAppletInfo);
        return wechatAppletInfo;
    }

    /**
     * 获取授权账号信息
     * @authorizerAppid 授权方appid
     */
    @PostMapping("/getAuthorizerInfo")
    public JSONObject AuthorizerInfo(@RequestBody String authorizationType){
        HashMap authorizerInfoMap = wechatMiniService.getAuthorizerInfo(authorizationType,null);
        JSONObject authorizerInfoJson = new JSONObject(authorizerInfoMap);

//        WechatAllworkReturn wechatAllworkReturn = new WechatAllworkReturn(String.valueOf(authorizerInfoMap.get("nickName")),String.valueOf(authorizerInfoMap.get("headImg")),
//                String.valueOf(authorizerInfoMap.get("userName")),String.valueOf(authorizerInfoMap.get("principalName")),String.valueOf(authorizerInfoMap.get("businessInfo")),
//                String.valueOf(authorizerInfoMap.get("qrcodeUrl")),String.valueOf(authorizerInfoMap.get("MiniProgramInfo")),String.valueOf(authorizerInfoMap.get("funcInfo")));
        logger.info("获取授权账号信息Json："+authorizerInfoJson);
        return authorizerInfoJson;
    }

//    /**
//     * 设置服务器域名
//     *
//     */
//    @PostMapping("/editDomain")
//    public String modifyDomain(@RequestBody String action){
//        logger.info("开始设置服务器域名,操作类型为"+action);
//        String rst =  wechatMiniService.modifyDomain(action,null);
//        return rst;
//    }

//    /**
//     * 设置业务域名
//     *
//     */
//    @PostMapping("/setwebviewdomain")
//    public String setwebviewdomain(@RequestBody(required = false) String action){
//        logger.info("开始设置业务域名,操作类型为"+action);
//        String rst =  wechatMiniService.setwebviewdomain(action,null);
//        return rst;
//    }


    /**
     * 绑定微信用户为体验者
     */
    @PostMapping("/bindTester")
    public String bindTester(@RequestBody String bindTesterJson){
        JSONObject jsonObject = JSONObject.parseObject(bindTesterJson);
        String wechatid =  jsonObject.getString("experienceId");
        String authorizationType =  jsonObject.getString("authorizationType");
        logger.info("开始绑定微信用户为体验者...");
        String userstr = wechatMiniService.bindTester(wechatid,authorizationType);
        logger.info("userstr："+userstr);
        return userstr;
    }

    /**
     * 获取体验者列表
     */
    @PostMapping("/getbindTester")
    public String memberauthList(@RequestBody String authorizationType){
        logger.info("开始获取体验者列表...");
        String membersList =  wechatMiniService.getmemberauthList(authorizationType);
        logger.info("获取体验者列表返回值为=>"+membersList);
        return membersList;
    }

    /**
     * 解除绑定体验者
     */
    @PostMapping("/unbindTester")
    public String unbindTester(@RequestBody String bindTesterJson){
        JSONObject jsonObject = JSONObject.parseObject(bindTesterJson);
        String wechatid =  jsonObject.getString("experienceId");
        String authorizationType =  jsonObject.getString("authorizationType");
        logger.info("开始解除绑定体验者...");
        String rst =  wechatMiniService.unbindTester(wechatid,authorizationType);
        logger.info("解除绑定体验者返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取已设置的所有类目
     */
    @GetMapping("/getcategory")
    public List getcategory(@RequestBody String authorizationType){
        logger.info("开始获取已设置的所有类目...");
        List rst =  wechatMiniService.getcategory(authorizationType);
        logger.info("获取已设置的所有类目返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取可设置的所有类目
     */
    @GetMapping("/getallcategories")
    public List<CanSetCategoryInfoVo> getallcategories(@RequestBody String authorizationType){
        logger.info("获取可设置的所有类目...");
        List<CanSetCategoryInfoVo> rst =  wechatMiniService.getallcategories(authorizationType);
        logger.info("获取可设置的所有类目返回值为=>"+rst);
        return rst;
    }

    /**
     * 添加类目
     */
    @PostMapping("/addcategory")
    public String addcategory(@RequestBody String categoryJson){
        logger.info("接受值=>"+categoryJson);
        JSONObject jsonObject = JSONObject.parseObject(categoryJson);
        String first =  jsonObject.getString("first");
        String second =  jsonObject.getString("second");
        String authorizationType =  jsonObject.getString("authorizationType");
//        String key =  jsonObject.getString("key");
//        String value =  jsonObject.getString("value");
        String key =  "";
        String value =  "";
        logger.info("开始添加类目...");
        String rst =  wechatMiniService.addcategory(first,second,key,value,authorizationType);
        logger.info("添加类目返回值为=>"+rst);
        return rst;
    }

    /**
     * 删除类目
     */
    @PostMapping("/deletecategory")
    public String deletecategory(@RequestBody String deletecategoryJson){
        JSONObject jsonObject = JSONObject.parseObject(deletecategoryJson);
        String first =  jsonObject.getString("first");
        String second =  jsonObject.getString("second");
        String authorizationType =  jsonObject.getString("authorizationType");
        logger.info("开始删除类目...");
        String rst =  wechatMiniService.deletecategory(first,second,authorizationType);
        logger.info("删除类目返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取小程序违规处罚记录
     *
     */
    @PostMapping("/getillegalrecords")
    public String getillegalrecords(@RequestBody String authorizationType){
        logger.info("开始获取小程序违规处罚记录");
        String rst =  wechatMiniService.getillegalrecords(authorizationType);
        logger.info("获取小程序违规处罚记录返回值为=>"+rst);
        return rst;
    }

    /**
     *获取小程序申诉记录
     * @param
     */
    @PostMapping("/getappealrecords")
    public  List<AppealRecord> getappealrecords(@RequestBody String appealrecordJosn){
        JSONObject jsonObject = JSONObject.parseObject(appealrecordJosn);
        String illegalRecordId = jsonObject.getString("illegalRecordId");
        String authorizationType = jsonObject.getString("authorizationType");
        logger.info("开始获取小程序申诉记录...");
        List<AppealRecord> rst =  wechatMiniService.getappealrecords(illegalRecordId,authorizationType);
        logger.info("获取小程序申诉记录返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取url link
     */
    @PostMapping("/generateUrllink")
    public String generateUrllink(@RequestBody String authorizationType){
        logger.info("开始获取urlLink...");
        String rst =  wechatMiniService.generateUrllink(authorizationType);
        logger.info("获取urlLink返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取小程序scheme码
     */
    @PostMapping("/generatescheme")
    public String generatescheme(@RequestBody String authorizationType){
        logger.info("开始获取小程序scheme码...");
        String rst =  wechatMiniService.generatescheme(authorizationType);
        logger.info("获取小程序scheme码返回值为=>"+rst);
        return rst;
    }

    /**
     * 设置名称
     */
    @PostMapping("/setAppletName")
    public String setAppletName(@RequestBody String appletInfoJson){
        JSONObject jsonObject = JSONObject.parseObject(appletInfoJson);
        String nickName = jsonObject.getString("nickName");
        String media_id = jsonObject.getString("media_id");
        String authorizationType = jsonObject.getString("authorizationType");
        logger.info("开始设置名称,请求参数为昵称:"+nickName+"组织号media_id:"+media_id);
        String rst =  wechatMiniService.setAppletName(nickName,media_id,authorizationType);
        return rst;
    }

    /**
     * 修改头像
     */
    @PostMapping("/modifyheadimage")
    public String modifyheadimage(@RequestBody String headimageJson){
        JSONObject jsonObject = JSONObject.parseObject(headimageJson);
        String authorizationType = jsonObject.getString("authorizationType");
        String headImgMediaId = jsonObject.getString("headImgMediaId");
        //裁剪框左上角 x 坐标（取值范围：[0, 1]）
        String x1 = jsonObject.getString("x1");
        //裁剪框左上角 y 坐标（取值范围：[0, 1]）
        String y1 = jsonObject.getString("y1");
        //裁剪框右下角 x 坐标（取值范围：[0, 1]）
        String x2 = jsonObject.getString("x2");
        //裁剪框右下角 y 坐标（取值范围：[0, 1]）
        String y2 = jsonObject.getString("y2");
        logger.info("开始修改头像,请求参数为头像media_id:"+headImgMediaId+"x1:"+x1+"y1:"+y1+"x2"+x2+"y2"+y2);
        String rst =  wechatMiniService.modifyheadimage(headImgMediaId,x1,y1,x2,y2,authorizationType);
        logger.info("设置名称返回值为=>"+rst);
        return rst;
    }

    /**
     * 修改简介
     */
    @PostMapping("/modifysignature")
    public String modifysignature(@RequestBody String modifysignatureJson){
        JSONObject jsonObject = JSONObject.parseObject(modifysignatureJson);
        String signature = jsonObject.getString("signature");
        String authorizationType = jsonObject.getString("authorizationType");
        logger.info("开始修改简介");
        String rst =  wechatMiniService.modifysignature(signature,authorizationType);
        logger.info("修改简介返回值为=>"+rst);
        return rst;
    }

    /**
     * 新增临时素材
     */
    @PostMapping("/saveTemporaryMaterial")
    public JSONObject saveTemporaryMaterial(HttpServletRequest request) throws Exception {
        String platformid = request.getParameter("platformid");
        String authorizationType = request.getParameter("authorizationType");
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        if (files != null && files.size()>0){
            file = files.get(0);
            logger.info("收到{}个文件，文件名为：{}",files.size(),file.getName());
        }else{
            logger.info("没有收到文件");
        }
        logger.info("文件名 fileName={}",file.getResource().getFilename());
        logger.info("文件名 getOriginalFilename={}",file.getOriginalFilename());
        File f = new File(file.getResource().getFilename());
        FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        JSONObject rst = wechatMiniService.uploadMedia("image", platformid,authorizationType, f);
        logger.info("新增临时素材返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取临时素材
     */
    @PostMapping("/getTemporaryMaterial")
    public String getTemporaryMaterial(@RequestBody String mediaJson){
        JSONObject jsonObject = JSONObject.parseObject(mediaJson);
        String mediaId = jsonObject.getString("mediaId");
        String authorizationType = jsonObject.getString("authorizationType");
        logger.info("开始获取临时素材,mediaId为:"+mediaId);
        String rst =  wechatMiniService.getTemporaryMaterial(mediaId,authorizationType);
        logger.info("获取临时素材返回值为=>"+rst);
        return rst;
    }

    /**
     * 设置支付方式
     */
    @PostMapping("/setPaymentType")
    public String setPaymentType(@RequestBody String setPaymentJson){
        JSONObject jsonObject = JSONObject.parseObject(setPaymentJson);
        String MerchantID =  jsonObject.getString("MerchantID");
        String authorizationType =  jsonObject.getString("authorizationType");
        logger.info("开始设置支付方式商户id为"+MerchantID);
        String rst =  wechatMiniService.setPaymentType(MerchantID,authorizationType);
        logger.info("设置支付方式返回值为=>"+rst);
        return rst;
    }

    /**
     * 获取平台id
     */
    @GetMapping("/getPlatFromId")
    public Long getPlatFromId(){
       return SecurityUtils.getPlatformId();
    }


//    /**
//     * 查询支付授权状态
//     * @return
//     */
//    @GetMapping("/getPayAuditStatus")
//    public AuditResult getPayAuditStatus(){
//        AuditResult payAuditStatus = wechatPayAuditService.getPayAuditStatus();
//        return payAuditStatus;
//    }

    /**
     * 查询申请单状态
     */
//    @ApiOperation(value = "查询申请单状态")
//    @Log(title = "查询申请单状态", businessType = BusinessType.GRANT)
//    @GetMapping("/getPayAuditStatus")
//    public AjaxResult getPayAuditStatus() {
//        return AjaxResult.success(wechatPayAuditService.getPayAuditStatus());
//    }
}
